#!/usr/bin/env python

import socket
import sys
import array

## Global Variables... I know this is not proper programming but I don't care

byte0 = chr(0xFF)
byte1 = chr(0x00)
id1 = chr(0x1e)
id2 = chr(0x19)
id3 = chr(0x0d)
m1 = chr(0x00)
m2 = chr(0x00)
m3 = chr(0x00)

fwd = chr(0x05)
rev = chr(0x0a)

dir1 = ''
dir2 = ''
dir3 = ''

transmitB = [byte0, byte1, id1, dir1, m1, id2, dir2, m3, id3, dir3, m3]

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def alert(msg):
	print >>sys.stderr, msg
	sys.exit(1)

def connectSrv():
	host = '192.168.1.138'
	port = 50003
	size = 100
	
	try:
		s.connect((host,port))
		print '\nConnecting to server...\n'
	except Exception, e:
		alert('Something is wrong with %s:%d. Exception is type %s' % (host, port, e))
	print 'Connection Established!!!\n'

def txBender(transmit):
	print 'Sending %s over tubes\n' % (transmit)
	s.send(transmit)

def wButton():
	global m1, m2, m3, dir1, dir2, dir3
	m1 += chr(0x05)
	dir1 = chr(0x05)
	m2 = chr(0x00)
	dir2 = chr(0x05)
	m3 += chr(0x05)
	dir3 = chr(0x06)
	transmit = ''
	transmitc = [byte0, byte1, id1, dir1, m1, id2, dir2, m3, id3, dir3, m3]
	for x in transmitc:
		transmit = transmit + x
	txBender(transmit)

def sButton():
	global m1, m2, m3, dir1, dir2, dir3
	m1 += chr(0x05)
	dir1 = chr(0x06)
	m2 = chr(0x00)
	dir2 = chr(0x06)
	m3 += chr(0x05)
	dir3 = chr(0x05)
	transmit = ''
	transmitc = [byte0, byte1, id1, dir1, m1, id2, dir2, m3, id3, dir3, m3]
	for x in transmitc:
		transmit = transmit + x
	txBender(transmit)

def dButton():
	global m1, m2, m3, dir1, dir2, dir3
	m1 += chr(0x05)
	dir1 = chr(0x06)
	m2 = chr(0x00)
	dir2 = chr(0x06)
	m3 += chr(0x05)
	dir3 = chr(0x06)
	transmit = ''
	transmitc = [byte0, byte1, id1, dir1, m1, id2, dir2, m3, id3, dir3, m3]
	for x in transmitc:
		transmit = transmit + x
	txBender(transmit)

def aButton():
	global m1, m2, m3, dir1, dir2, dir3
	m1 = chr(0x00)
	dir1 = chr(0x06)
	m2 = chr(0x20)
	dir2 = chr(0x06)
	m3 = chr(0x20)
	dir3 = chr(0x06)
	transmit = ''
	transmitc = [byte0, byte1, id1, dir1, m1, id2, dir2, m3, id3, dir3, m3]
	for x in transmitc:
		transmit = transmit + x
	txBender(transmit)

def stp():
	global m1, m2, m3, dir1, dir2, dir3
	m1 = chr(0x00)
	dir1 = chr(0x0a)
	m2 = chr(0x00)
	dir2 = chr(0x0a)
	m3 = chr(0x00)
	dir3 = chr(0x0a)
	transmit = ''
	transmitc = [byte0, byte1, id1, dir1, m1, id2, dir2, m3, id3, dir3, m3]
	for x in transmitc:
		transmit = transmit + x
	txBender(transmit)

running = 1

connectSrv()
while running:
	choice = raw_input('\n...you know the commands...\n')
	if choice == 'w':
		wButton()
	elif choice == 's':
		sButton()
	elif choice == 'a':
		aButton()
	elif choice == 'd':
		dButton()
	elif choice == 'st':
		stp()
	else:
		print 'Exiting...\n'
		running = 0
s.close()
exit()
